package com.thams.util;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;

public class ParseRequestUtils {

	public static Object parseRequest(HttpServletRequest request, Object bean) {
		// 取得所有参数列表
		Enumeration enumObj = request.getParameterNames();
		// 遍历所有参数列表
		while (enumObj.hasMoreElements()) {

			Object obj = enumObj.nextElement();
			try {
				// 取得这个参数在Bean中的数据类开
				Class cls = PropertyUtils.getPropertyType(bean, obj.toString());
				if(cls==null){
					continue;
				}
				// 把相应的数据转换成对应的数据类型
				Object beanValue = ConvertUtils.convert(new String(request.getParameter(obj.toString()).getBytes("iso-8859-1"),"utf-8"), cls);
				// 添冲Bean值
				PropertyUtils.setProperty(bean, obj.toString(), beanValue);
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return bean;
	}
}